package com.wtwd.campus.jdzc.controller;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.jdzc.common.RespCode;
import com.wtwd.campus.jdzc.common.RespEntity;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.service.DeviceWhiteListService;
import com.wtwd.campus.jdzc.common.Constant;
import com.wtwd.campus.jdzc.service.ValidService;
import com.wtwd.campus.service.LogService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.CommandSendUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: ldaoliang
 * @DateTime: 2022/2/14 16:30
 * @Description:
 * 号码类
 */
@RestController
@RequestMapping("/jdzc/phone")
public class JdzcPhoneController {


    private static final Logger logger = LoggerFactory.getLogger(JdzcPhoneController.class);

    @Autowired
    private DeviceWhiteListService deviceWhiteListService;
    @Autowired
    private ValidService validService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CommandSendUtils commandSendUtils;
    @Autowired
    private LogService logService;
    /**
     * 亲情号列表
     * @param studentId
     * @param request
     * @return
     */
    @GetMapping("/affectionList/{stuId}")
    public RespEntity affectionList(@PathVariable("stuId")Integer studentId, HttpServletRequest request){
        logger.info("获取亲情号列表： studentId = {}",studentId);
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        boolean isCorrespond = validService.validStudentAndTokenCorrespond(studentId,token);
        if(!isCorrespond){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }
        List<DeviceWhiteList> whiteList = deviceWhiteListService.getAffectionNumberByStuId(studentId);
        if (whiteList != null && whiteList.size() > 0) {
            whiteList = whiteList.stream().filter(white -> white.getSequence() > 3 && white.getSequence() < 7).collect(Collectors.toList());
        }
        return new RespEntity(RespCode.SUCCESS,whiteList);
    }

    /**
     * 添加号码
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping("/addAffection")
    public RespEntity addAffection(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        logger.info("添加亲情号，param = " + jsonObject);
        Integer studentId = jsonObject.getInteger("studentId");
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        Integer sequence = jsonObject.getInteger("sequence");
        if(sequence > 6 || sequence < 4){
            return new RespEntity(RespCode.SEQUENCE_ILLEGAL);
        }
        // 校验设备是否存在
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.NO_DEVICE);
        }
        // 校验号码是否相同
        String phone = jsonObject.getString("number");
        String name = jsonObject.getString("name");
        List<DeviceWhiteList> list = deviceWhiteListService.getAffectionNumberByStuId(studentId);
        boolean isRepeat = list.stream().filter(white -> white.getSequence() > 3 && white.getSequence() < 7).anyMatch(white -> white.getWhitePhone().equals(phone));
        if(isRepeat){
            return new RespEntity(RespCode.PHONE_REPEAT);
        }
        boolean sequenceExistPhone = list.stream().filter(white -> white.getSequence() > 3 && white.getSequence() < 7).anyMatch(white -> white.getSequence()== sequence);
        if(sequenceExistPhone){
            return new RespEntity(RespCode.SEQUENCE_EXIST_PHONE);
        }
        DeviceWhiteCall deviceWhiteCall = new DeviceWhiteCall();
        deviceWhiteCall.setImei(deviceInfo.getImei());
        deviceWhiteCall.setCommandNumber(getCurTime());
        deviceWhiteCall.setSequence(sequence);
        deviceWhiteCall.setPhone(phone);
        deviceWhiteCall.setName(name);
        deviceWhiteCall.setDeviceId(deviceInfo.getDeviceId());
        deviceWhiteCall.setStatus(Constants.WHITE_PATTERN_STAY_ADD);
        deviceWhiteCall.setIsAffection(1);
        //进行亲情号的添加
        Integer i = deviceWhiteListService.addDeviceWhiteList(deviceWhiteCall);
        if (i > 0) {
            //进行指令下发添加亲情号
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            boolean sendResult = commandSendUtils.addWhiteCall(deviceWhiteCall, isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (sendResult) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 删除亲情号
     * @param studentId
     * @param id
     * @param request
     * @return
     */
    @DeleteMapping("/delAffection/{studentId}/{id}")
    public RespEntity delAffection(@PathVariable("studentId")Integer studentId,@PathVariable("id")Integer id,HttpServletRequest request){
        logger.info("删除亲情号： studentId = {},id = {}",studentId,id);
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        // 判断亲情号和学生对应的号码是否一样
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        DeviceWhiteList deviceWhiteList = deviceWhiteListService.getDeviceWhiteListById(id);
        if(deviceInfo == null) {
            return new RespEntity(RespCode.NO_DEVICE);
        }
        if(deviceWhiteList == null){
            return new RespEntity(RespCode.DATA_NOT_FOUND);
        }
        if(!deviceInfo.getDeviceId().equals(deviceWhiteList.getDeviceId())){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        if(deviceWhiteList.getStatus() != Constant.STATUS_NORMAL){  // 非正常状态不能操作
            return new RespEntity(RespCode.COMMAND_NOT_COMPLETE_CAN_NO_OPERATION);
        }
        deviceWhiteList.setStatus(Constants.WHITE_PATTERN_STAY_DELETE);
        Integer i = deviceWhiteListService.modifyAffectionNumber(deviceWhiteList);
        if (i > 0) {
            //进行指令下发删除亲情号
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            boolean b1 = commandSendUtils.delWhiteCall(deviceInfo.getImei(), getCurTime(), deviceWhiteList.getSequence(), isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (b1) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 更新亲情号
     * @param white
     * @param request
     * @return
     */
    @PutMapping("/updateAffection")
    public RespEntity updateAffection(@RequestBody DeviceWhiteList white, HttpServletRequest request){
        DeviceWhiteList deviceWhiteList = deviceWhiteListService.getDeviceWhiteListById(white.getId());
        if(deviceWhiteList == null){
            return new RespEntity(RespCode.DATA_NOT_FOUND);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByDeviceId(deviceWhiteList.getDeviceId());
        Integer studentId = deviceInfo.getStudentId();
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        if(deviceWhiteList.getStatus() != Constant.STATUS_NORMAL){  // 非正常状态不能操作
            return new RespEntity(RespCode.COMMAND_NOT_COMPLETE_CAN_NO_OPERATION);
        }
        // 避免号码重复
        List<DeviceWhiteList> list = deviceWhiteListService.getAffectionNumberByStuId(studentId);
        boolean isRepeat = list.stream().filter(w -> w.getSequence() > 3 && w.getSequence() < 7)
                .anyMatch(w -> w.getWhitePhone().equals(white.getWhitePhone()));
        if(isRepeat){
            return new RespEntity(RespCode.PHONE_REPEAT);
        }
        white.setStatus(Constants.WHITE_PATTERN_STAY_UPDATE);
        Integer i = deviceWhiteListService.modifyAffectionNumber(white);
        if(i > 0){
            DeviceWhiteCall deviceWhiteCall = new DeviceWhiteCall();
            deviceWhiteCall.setImei(deviceInfo.getImei());
            deviceWhiteCall.setCommandNumber(getCurTime());
            deviceWhiteCall.setSequence(deviceWhiteList.getSequence());
            deviceWhiteCall.setPhone(white.getWhitePhone());
            deviceWhiteCall.setName(white.getWhiteName());
            deviceWhiteCall.setDeviceId(deviceInfo.getDeviceId());
            deviceWhiteCall.setStatus(Constants.WHITE_PATTERN_STAY_UPDATE);
            deviceWhiteCall.setIsAffection(1);
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            boolean b1 = commandSendUtils.updateDeviceWhiteCall(deviceWhiteCall, isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (b1) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 亲情号列表
     * @param studentId
     * @param request
     * @return
     */
    @GetMapping("/whiteList/{stuId}")
    public RespEntity whiteList(@PathVariable("stuId")Integer studentId, HttpServletRequest request){
        logger.info("获取通讯录列表： studentId = {}",studentId);
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        boolean isCorrespond = validService.validStudentAndTokenCorrespond(studentId,token);
        if(!isCorrespond){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }
        List<DeviceWhiteList> whiteList = deviceWhiteListService.getAffectionNumberByStuId(studentId);
        if (whiteList != null && whiteList.size() > 0) {
            whiteList = whiteList.stream().filter(white -> white.getSequence() > 6).collect(Collectors.toList());
        }
        return new RespEntity(RespCode.SUCCESS,whiteList);
    }

    /**
     * 添加号码
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping("/addWhiteList")
    public RespEntity addWhiteList(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        logger.info("添加通讯录，param = " + jsonObject);
        Integer studentId = jsonObject.getInteger("studentId");
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        // 校验设备是否存在
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.NO_DEVICE);
        }
        // 校验号码是否相同
        String phone = jsonObject.getString("number");
        String name = jsonObject.getString("name");
        List<DeviceWhiteList> list = deviceWhiteListService.getAffectionNumberByStuId(studentId);
        boolean isRepeat = list.stream().filter(white -> white.getSequence() > 6)
                .anyMatch(white -> white.getWhitePhone().equals(phone));
        if(isRepeat){
            return new RespEntity(RespCode.PHONE_REPEAT);
        }
        Integer sequence = getSequenceInLink(list);
        if (sequence == 0) {
            return new RespEntity(RespCode.WHITE_LIST_FULL);
        }
        DeviceWhiteCall deviceWhiteCall = new DeviceWhiteCall();
        deviceWhiteCall.setImei(deviceInfo.getImei());
        deviceWhiteCall.setCommandNumber(getCurTime());
        deviceWhiteCall.setSequence(sequence);
        deviceWhiteCall.setPhone(phone);
        deviceWhiteCall.setName(name);
        deviceWhiteCall.setDeviceId(deviceInfo.getDeviceId());
        deviceWhiteCall.setStatus(Constants.WHITE_PATTERN_STAY_ADD);
        deviceWhiteCall.setIsAffection(0);
        //进行亲情号的添加
        Integer i = deviceWhiteListService.addDeviceWhiteList(deviceWhiteCall);
        if (i > 0) {
            //进行指令下发添加亲情号
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            boolean sendResult = commandSendUtils.addWhiteCall(deviceWhiteCall, isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (sendResult) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 更新白名单
     * @param jsonObject
     * @param request
     * @return
     */
    @PutMapping("/updateWhiteList")
    public RespEntity updateWhiteList(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        Integer id = jsonObject.getInteger("id");
        String name = jsonObject.getString("whiteName");
        String phone = jsonObject.getString("whitePhone");
        DeviceWhiteList deviceWhiteList = deviceWhiteListService.getDeviceWhiteListById(id);
        if(deviceWhiteList == null){
            return new RespEntity(RespCode.DATA_NOT_FOUND);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByDeviceId(deviceWhiteList.getDeviceId());
        Integer studentId = deviceInfo.getStudentId();
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        if(deviceWhiteList.getStatus() != Constant.STATUS_NORMAL){  // 非正常状态不能操作
            return new RespEntity(RespCode.COMMAND_NOT_COMPLETE_CAN_NO_OPERATION);
        }
        // 避免号码重复
        List<DeviceWhiteList> list = deviceWhiteListService.getAffectionNumberByStuId(studentId);
        boolean isRepeat = list.stream().filter(white -> white.getSequence() > 6)
                .anyMatch(white -> white.getWhitePhone().equals(phone));
        if(isRepeat){
            return new RespEntity(RespCode.PHONE_REPEAT);
        }
        DeviceWhiteCall deviceWhiteCall = new DeviceWhiteCall();
        deviceWhiteCall.setImei(deviceInfo.getImei());
        deviceWhiteCall.setCommandNumber(getCurTime());
        deviceWhiteCall.setSequence(deviceWhiteList.getSequence());
        deviceWhiteCall.setPhone(phone);
        deviceWhiteCall.setName(name);
        deviceWhiteCall.setDeviceId(deviceInfo.getDeviceId());
        deviceWhiteCall.setStatus(Constants.WHITE_PATTERN_STAY_UPDATE);
        deviceWhiteCall.setIsAffection(0);
        boolean isOnline = deviceOnline(deviceInfo.getImei());
        boolean b1 = commandSendUtils.updateDeviceWhiteCall(deviceWhiteCall, isOnline, Constants.WX_COMMAND_USER_ID, false);
        if (b1) {
            return new RespEntity(RespCode.SUCCESS);
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 删除亲情号
     * @param studentId
     * @param id
     * @param request
     * @return
     */
    @DeleteMapping("/delWhiteList/{studentId}/{id}")
    public RespEntity delWhiteList(@PathVariable("studentId")Integer studentId,@PathVariable("id")Integer id,HttpServletRequest request){
        logger.info("删除白名单： studentId = {},id = {}",studentId,id);
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        // 判断亲情号和学生对应的号码是否一样
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        DeviceWhiteList deviceWhiteList = deviceWhiteListService.getDeviceWhiteListById(id);
        if(deviceInfo == null) {
            return new RespEntity(RespCode.NO_DEVICE);
        }
        if(deviceWhiteList == null){
            return new RespEntity(RespCode.DATA_NOT_FOUND);
        }
        if(!deviceInfo.getDeviceId().equals(deviceWhiteList.getDeviceId())){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        if(deviceWhiteList.getStatus() != Constant.STATUS_NORMAL){  // 非正常状态不能操作
            return new RespEntity(RespCode.COMMAND_NOT_COMPLETE_CAN_NO_OPERATION);
        }
        deviceWhiteList.setStatus(Constants.WHITE_PATTERN_STAY_DELETE);
        Integer i = deviceWhiteListService.modifyAffectionNumber(deviceWhiteList);
        if (i > 0) {
            //进行指令下发删除亲情号
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            boolean b1 = commandSendUtils.delWhiteCall(deviceInfo.getImei(), getCurTime(), deviceWhiteList.getSequence(), isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (b1) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * sos列表
     * @return
     */
    @GetMapping("/sosList/{studentId}")
    public RespEntity sosList(@PathVariable("studentId")Integer studentId,HttpServletRequest request){
        logger.info("获取SOS号码列表：studentId = {}",studentId);
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        boolean isCorrespond = validService.validStudentAndTokenCorrespond(studentId,token);
        if(!isCorrespond){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.NO_DEVICE);
        }
        //获取sos列表
        List<DeviceSOSList> sosList = logService.getSOSListByDeviceId(deviceInfo.getDeviceId());
        return new RespEntity(RespCode.SUCCESS,sosList);
    }

    /**
     * 添加SOS号码
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/addSos")
    public RespEntity addSos(@RequestBody SOSListVO data, HttpServletRequest request){
        logger.info("添加SOS号码 ： param = {}",data);
        Integer studentId = data.getStudentId();
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.NO_DEVICE);
        }
        //获取该设备已经存在的SOS告警记录
        List<DeviceSOSList> sosList = logService.getSOSListByDeviceId(deviceInfo.getDeviceId());
        Integer sequence = getSosSequence(sosList);
        if (sequence == 0) {
            return new RespEntity(RespCode.SOS_FULL);
        }
        for (DeviceSOSList sos : sosList) {
            if (sos.getSosPhone().equals(data.getPhone())) {
                return new RespEntity(RespCode.PHONE_REPEAT);
            }
        }
        String commandNumber = getCurTime();
        DeviceSOSList sos = new DeviceSOSList();
        sos.setDeviceId(deviceInfo.getDeviceId());
        sos.setCommandNumber(commandNumber);
        sos.setSequence(sequence);
        sos.setSosName(data.getName());
        sos.setSosPhone(data.getPhone());
        sos.setStatus(Constants.DEVICE_SOS_STAY_ADD);
        //在数据库添加一笔SOS号码信息
        int i = logService.insertSosNumberList(sos);
        if (i > 0) {
            //指令下发进行添加SOS号码
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            List<DeviceSOSList> actually = getAddSetSOSList(sos, deviceInfo.getDeviceId());
            boolean b1 = commandSendUtils.setAllSosCall(actually, deviceInfo.getImei(), commandNumber, isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (b1) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 删除SOS号码
     * @param studentId
     * @param id
     * @param request
     * @return
     */
    @DeleteMapping("/delSos/{studentId}/{id}")
    public RespEntity delSOS(@PathVariable("studentId")Integer studentId, @PathVariable("id")Integer id, HttpServletRequest request){
        logger.info("删除SOS号码 ： studentId = {},id = {}",studentId,id);
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        DeviceSOSList deviceSOSMessById = logService.getDeviceSOSMessById(id);
        if(deviceInfo == null){
            return new RespEntity(RespCode.NO_DEVICE);
        }
        if(deviceSOSMessById == null) {
            return new RespEntity(RespCode.DATA_NOT_FOUND);
        }
        if(!deviceSOSMessById.getDeviceId().equals(deviceInfo.getDeviceId())){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        if(deviceSOSMessById.getStatus() != Constant.STATUS_NORMAL){
            return new RespEntity(RespCode.COMMAND_NOT_COMPLETE_CAN_NO_OPERATION);
        }
        //将sos号码信息的状态设置为待删除
        String commandNumber = getCurTime();
        Integer i = logService.updateSosListStatus(id, Constants.DEVICE_SOS_DELETE, commandNumber);
        if (i > 0) {
            DeviceSOSList sos = new DeviceSOSList();
            sos.setDeviceId(deviceInfo.getDeviceId());
            sos.setCommandNumber(commandNumber);
            sos.setSequence(deviceSOSMessById.getSequence());
            sos.setSosName("");
            sos.setSosPhone("");
            //进行指令下发删除亲情号
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            List<DeviceSOSList> sosList = getDelSetSOSList(sos, deviceInfo.getDeviceId());
            boolean b1 = commandSendUtils.setAllSosCall(sosList, deviceInfo.getImei(), commandNumber, isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (b1) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * 修改SOS号码
     * @param data
     * @param request
     * @return
     */
    @PutMapping("/updateSos")
    public RespEntity updateSos(@RequestBody SOSListVO data, HttpServletRequest request){
        logger.info("修改SOS号码 ： param = {}",data);
        Integer studentId = data.getStudentId();
        Integer id = data.getId();
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        DeviceSOSList deviceSOSMessById = logService.getDeviceSOSMessById(id);
        if(deviceInfo == null){
            return new RespEntity(RespCode.NO_DEVICE);
        }
        if(deviceSOSMessById == null) {
            return new RespEntity(RespCode.DATA_NOT_FOUND);
        }
        if(!deviceSOSMessById.getDeviceId().equals(deviceInfo.getDeviceId())){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        if(deviceSOSMessById.getStatus() != Constant.STATUS_NORMAL){
            return new RespEntity(RespCode.COMMAND_NOT_COMPLETE_CAN_NO_OPERATION);
        }
        //获取流水号
        String commandNumber = getCurTime();
        DeviceSOSList sos = new DeviceSOSList();
        sos.setDeviceId(deviceInfo.getDeviceId());
        sos.setCommandNumber(commandNumber);
        sos.setSequence(data.getSequence());
        sos.setSosName(data.getName());
        sos.setSosPhone(data.getPhone());
        sos.setStatus(Constants.DEVICE_SOS_STAY_UPDATE);
        //修改SOS号码的状态为待修改同时修改数据库内容
        Integer i = logService.updateSosListData(data, Constants.DEVICE_SOS_STAY_UPDATE, commandNumber);
        //修改SOS号码的状态为待修改
        if (i > 0) {
            //指令下发进行修改SOS信息
            boolean isOnline = deviceOnline(deviceInfo.getImei());
            List<DeviceSOSList> modifySOSList = getModifySetSOSList(sos, deviceInfo.getDeviceId());
            boolean b1 = commandSendUtils.setAllSosCall(modifySOSList, deviceInfo.getImei(), commandNumber, isOnline, Constants.WX_COMMAND_USER_ID, false);
            if (b1) {
                return new RespEntity(RespCode.SUCCESS);
            }
        }
        return new RespEntity(RespCode.FAILED);
    }

    /**
     * sos详情
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/sosDetail/{id}")
    public RespEntity sosDetail(@PathVariable("id")Integer id,HttpServletRequest request){
       DeviceSOSList deviceSOSMessById = logService.getDeviceSOSMessById(id);
        if(deviceSOSMessById == null){
            return new RespEntity(RespCode.DATA_NOT_FOUND);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByDeviceId(deviceSOSMessById.getDeviceId());
        if(deviceInfo == null){
            return new RespEntity(RespCode.NO_DEVICE);
        }
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        boolean validResult = validService.validStudentAndTokenCorrespond(deviceInfo.getStudentId(),token);
        if(!validResult){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }
        //根据id查找SOS记录
        DeviceSOSList sos = logService.getDeviceSOSMessById(id);
        return new RespEntity(sos == null ? RespCode.FAILED : RespCode.SUCCESS, sos);
    }

    /**
     * 设置监听号码
     * @param jsonObject
     * @param request
     * @return
     */
    @PutMapping("/setMonitorNumber")
    public RespEntity setMonitorNumber(@RequestBody JSONObject jsonObject,HttpServletRequest request){
        Integer studentId = jsonObject.getInteger("studentId");
        String number = jsonObject.getString("number");
        String token = request.getHeader(Constant.HEADER_TOKEN_KEY);
        int validResult = validService.validCanOperation(studentId,token);
        if(validResult == 0){
            return new RespEntity(RespCode.ILLEGAL_OPERATION);
        }else if(validResult == 1){
            return new RespEntity(RespCode.NO_PERMISSION);
        }
        DeviceInfo deviceInfo = deviceInfoService.getDeviceInfoByStuId(studentId);
        //判断设备是否在线
        boolean isOnline = deviceOnline(deviceInfo.getImei());
        if (!isOnline) {
            return new RespEntity(RespCode.DEVICE_NOT_ONLINE);
        }
        //查找该设备的设置信息
        DeviceSetting setting = deviceInfoService.getDeviceSettingByDeviceId(deviceInfo.getDeviceId());
        if (setting != null) {
            String commandNumber = getCurTime();
            setting.setMonitorNum(number);
            //修改设备设置信息
            int i = deviceInfoService.modifyDeviceInfoSetting(setting);
            if (i > 0) {
                //进行指令下发
                boolean sendResult = commandSendUtils.setMonitorPhone(deviceInfo.getImei(), commandNumber, number, Constants.WX_COMMAND_USER_ID);
                if (sendResult) {
                    return new RespEntity(RespCode.SUCCESS);
                }
            }
        }
        return new RespEntity(RespCode.FAILED);
    }


    /**
     * 获取修改下发设置SOS的参数
     */
    public List<DeviceSOSList> getModifySetSOSList(DeviceSOSList list, Integer deviceId) {
        //根据设备id查找SOS号码记录
        List<DeviceSOSList> sosList = logService.getSOSListByDeviceId(deviceId);
        Iterator<DeviceSOSList> iterator = sosList.iterator();
        while (iterator.hasNext()) {
            //将从数据库中查询出来的对应的要修改的老数据从list中删除
            DeviceSOSList next = iterator.next();
            if (next.getSequence() == list.getSequence()) {
                iterator.remove();
                continue;
            }
            //如果是碰到状态为待删除的，也将它移除
            if (next.getStatus().equals(Constants.DEVICE_WHITE_DELETE)) {
                iterator.remove();
            }
        }
        //修改界限
        List<Integer> sequenceList = sosList.stream()
                .map(DeviceSOSList::getSequence)
                .collect(Collectors.toList());
        for (int i = 1; i <= 3; i++) {
            //如果是修改的那笔数据的sequence，则直接把修改后的新数据加入进去
            if (i == list.getSequence()) {
                sosList.add(list);
                continue;
            }
            if (sequenceList.contains(i)) {
                continue;
            }
            DeviceSOSList deviceSOSList = new DeviceSOSList();
            deviceSOSList.setSequence(i);
            deviceSOSList.setSosName("");
            deviceSOSList.setSosPhone("");
            sosList.add(deviceSOSList);
        }
        sosList = sosList.stream()
                .sorted(Comparator.comparing(DeviceSOSList::getSequence))
                .collect(Collectors.toList());
        logger.info("---更新SOS" + sosList.toString());
        return sosList;
    }

    /**
     * 获取删除下发指令设置SOS的参数
     */
    public List<DeviceSOSList> getDelSetSOSList(DeviceSOSList list, Integer deviceId) {
        //根据设备id查找SOS号码记录
        List<DeviceSOSList> sosList = logService.getSOSListByDeviceId(deviceId);
        // 排除掉需要删除的，删除的用空
        Iterator iterator = sosList.iterator();
        while (iterator.hasNext()) {
            DeviceSOSList sos = (DeviceSOSList) iterator.next();
            if (sos.getSequence().equals(list.getSequence())) {
                iterator.remove();
                continue;
            }
            //如果是碰到状态为待删除的，也将它移除
            if (sos.getStatus().equals(Constants.DEVICE_WHITE_DELETE)) {
                iterator.remove();
            }
        }
        List<Integer> sequenceList = sosList.stream().map(DeviceSOSList::getSequence).collect(Collectors.toList());
        for (int i = 1; i <= 3; i++) {
            if (sequenceList.contains(i)) {
                continue;
            }
            DeviceSOSList deviceSOSList = new DeviceSOSList();
            deviceSOSList.setSequence(i);
            deviceSOSList.setSosName("");
            deviceSOSList.setSosPhone("");
            sosList.add(deviceSOSList);
        }
        sosList = sosList.stream()
                .sorted(Comparator.comparing(DeviceSOSList::getSequence))
                .collect(Collectors.toList());
        logger.info("---删除SOS" + sosList.toString());
        return sosList;
    }

    /**
     * 获取添加下发指令设置SOS的参数
     */
    public List<DeviceSOSList> getAddSetSOSList(DeviceSOSList list, Integer deviceId) {
        //根据设备id查找SOS号码记录，这里的sos记录会影响到下面的结果，因为如果是有2和3，则顺序就位231了
        List<DeviceSOSList> sosList = logService.getSOSListByDeviceId(deviceId);
        //修改内容
        Iterator<DeviceSOSList> iterator = sosList.iterator();
        while (iterator.hasNext()) {
            DeviceSOSList next = iterator.next();
            //如果数据库有待删除的数据，那么下发的时候需要下发空值，所以这里需要删除掉
            if (next.getStatus().equals(Constants.DEVICE_WHITE_DELETE)) {
                iterator.remove();
            }
        }
        //修改界限
        // 获取数据库有的id
        List<Integer> sequenceList = sosList.stream().map(DeviceSOSList::getSequence).collect(Collectors.toList());
        for (Integer i = 1; i <= 3; i++) {
            // 如果有，则不管，否则就加一个空的
            if (sequenceList.contains(i)) {
                continue;
            }
            DeviceSOSList deviceSOSList = new DeviceSOSList();
            deviceSOSList.setSequence(i);
            deviceSOSList.setSosName("");
            deviceSOSList.setSosPhone("");
            sosList.add(deviceSOSList);
        }
        // 排序
        sosList = sosList.stream().sorted(Comparator.comparing(DeviceSOSList::getSequence)).collect(Collectors.toList());
        logger.info("---新增SOS" + sosList.toString());
        return sosList;
    }




    /**
     * 获取一个可用的通讯录的序列号
     */
    public Integer getSequenceInLink(List<DeviceWhiteList> list) {
        List<Integer> seqList = new ArrayList<>();
        for (DeviceWhiteList deviceWhiteList : list) {
            seqList.add(deviceWhiteList.getSequence());
        }
        for (int i = 7; i <= 23; i++) {
            if (!seqList.contains(i)) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 获取一个可用的SOS列表的序列号
     */
    public Integer getSosSequence(List<DeviceSOSList> sosList) {
        List<Integer> seqList = new ArrayList<>();
        for (DeviceSOSList deviceSOSList : sosList) {
            seqList.add(deviceSOSList.getSequence());
        }
        for (int i = 1; i <= 3; i++) {
            if (!seqList.contains(i)) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 判断设备是否在线
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    public boolean deviceOnline(String imei) {
        boolean isOnline = redisService.hasKey(Constants.DEVICE_ONLINE_PREFIX + imei);
        logger.info("设备:【{}】: {}", imei, isOnline ? "在线" : "离线");
        return isOnline;
    }

    /**
     * 获取当前时间的时分秒（HHmmss）
     *
     * @return
     */
    public String getCurTime() {
        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");
        String format = sbf.format(d);
        String[] split = format.split(":");
        String time = split[0].concat(split[1]).concat(split[2]);
        return time;
    }
}
